<template>
  <div class="create-diary-container">
    <!-- 顶部标题栏 -->
    <div class="page-header">
      <el-button class="back-btn" circle @click="goBack">
        <el-icon><ArrowLeft /></el-icon>
      </el-button>
      <h1>✍️ 写日记</h1>
      <div class="placeholder"></div>
    </div>

    <!-- 日记表单 -->
    <div class="diary-form">
      <!-- 日记标题 -->
      <div class="form-section">
        <div class="section-label">
          <span class="required">*</span> 日记标题
        </div>
        <el-input
          v-model="form.title"
          placeholder="给今天的日记起个标题吧"
          maxlength="50"
          show-word-limit
          class="title-input"
        />
      </div>

      <!-- 今天心情 -->
      <div class="form-section">
        <div class="section-label">
          <span class="required">*</span> 今天心情
        </div>
        <div class="mood-options">
          <div
            v-for="mood in moodOptions"
            :key="mood.value"
            class="mood-item"
            :class="{ active: form.mood === mood.value }"
            @click="form.mood = mood.value"
          >
            <span class="mood-emoji">{{ mood.emoji }}</span>
            <span class="mood-text">{{ mood.label }}</span>
          </div>
        </div>
      </div>

      <!-- 今天天气 -->
      <div class="form-section">
        <div class="section-label">今天天气</div>
        <div class="weather-options">
          <div
            v-for="weather in weatherOptions"
            :key="weather.value"
            class="weather-item"
            :class="{ active: form.weather === weather.value }"
            @click="form.weather = weather.value"
          >
            <span class="weather-emoji">{{ weather.emoji }}</span>
            <span class="weather-text">{{ weather.label }}</span>
          </div>
        </div>
      </div>

      <!-- 日记内容 -->
      <div class="form-section">
        <div class="section-label-with-action">
          <div class="section-label">
            <span class="required">*</span> 日记内容
          </div>
          <el-button
            class="clear-btn"
            size="small"
            @click="clearContent"
            v-if="form.content.trim()"
          >
            🗑️ 清空
          </el-button>
        </div>
        <el-input
          v-model="form.content"
          type="textarea"
          :rows="10"
          placeholder="记录今天发生的事情..."
          maxlength="2000"
          show-word-limit
          class="content-textarea"
        />
      </div>

      <!-- 隐私设置 -->
      <div class="form-section privacy-section">
        <div class="privacy-label">隐私设置</div>
        <div class="privacy-switch">
          <span class="switch-label">{{ form.isPrivate ? '私密（只有我能看）' : '共享（TA也能看）' }}</span>
          <el-switch v-model="form.isPrivate" />
        </div>
      </div>

      <!-- 底部按钮 -->
      <div class="form-actions">
        <el-button class="submit-btn" type="primary" @click="submitForm" :loading="submitting">
          💾 保存日记
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, watch, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
import { createDiary } from '@/api'

const router = useRouter()
const submitting = ref(false)

// localStorage 的 key
const DRAFT_KEY = 'diary_draft'

const form = reactive({
  title: '',
  mood: 'happy',
  weather: '晴天',
  content: '',
  isPrivate: false
})

// 从 localStorage 加载草稿
const loadDraft = () => {
  try {
    const draft = localStorage.getItem(DRAFT_KEY)
    if (draft) {
      const data = JSON.parse(draft)
      form.title = data.title || ''
      form.mood = data.mood || 'happy'
      form.weather = data.weather || '晴天'
      form.content = data.content || ''
      form.isPrivate = data.isPrivate || false

      if (form.title || form.content) {
        ElMessage.info('已恢复上次未保存的草稿')
      }
    }
  } catch (error) {
    console.error('加载草稿失败:', error)
  }
}

// 保存草稿到 localStorage
const saveDraft = () => {
  try {
    const draft = {
      title: form.title,
      mood: form.mood,
      weather: form.weather,
      content: form.content,
      isPrivate: form.isPrivate,
      timestamp: Date.now()
    }
    localStorage.setItem(DRAFT_KEY, JSON.stringify(draft))
  } catch (error) {
    console.error('保存草稿失败:', error)
  }
}

// 清除草稿
const clearDraft = () => {
  try {
    localStorage.removeItem(DRAFT_KEY)
  } catch (error) {
    console.error('清除草稿失败:', error)
  }
}

// 监听表单变化，自动保存草稿
watch(form, () => {
  saveDraft()
}, { deep: true })

// 组件挂载时加载草稿
onMounted(() => {
  loadDraft()
})

// 组件卸载时保存草稿
onUnmounted(() => {
  saveDraft()
})

// 心情选项
const moodOptions = [
  { value: 'happy', emoji: '😊', label: '开心' },
  { value: 'sad', emoji: '😢', label: '难过' },
  { value: 'excited', emoji: '😆', label: '兴奋' },
  { value: 'calm', emoji: '😌', label: '平静' },
  { value: 'angry', emoji: '😠', label: '生气' },
  { value: 'love', emoji: '😍', label: '甜蜜' }
]

// 天气选项
const weatherOptions = [
  { value: '晴天', emoji: '☀️', label: '晴天' },
  { value: '多云', emoji: '⛅', label: '多云' },
  { value: '阴天', emoji: '☁️', label: '阴天' },
  { value: '雨天', emoji: '🌧️', label: '雨天' },
  { value: '雪天', emoji: '❄️', label: '雪天' }
]

// 清空内容
const clearContent = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要清空当前日记内容吗？此操作不可恢复。',
      '清空确认',
      {
        confirmButtonText: '确定清空',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'confirm-clear-btn'
      }
    )

    // 清空表单
    form.title = ''
    form.content = ''
    form.mood = 'happy'
    form.weather = '晴天'
    form.isPrivate = false

    // 清除草稿
    clearDraft()

    ElMessage.success('已清空日记内容')
  } catch (error) {
    // 用户取消操作
    if (error !== 'cancel') {
      console.error('清空内容失败:', error)
    }
  }
}

// 提交表单
const submitForm = async () => {
  // 验证必填项
  if (!form.title.trim()) {
    ElMessage.warning('请输入日记标题')
    return
  }
  if (!form.content.trim()) {
    ElMessage.warning('请输入日记内容')
    return
  }
  if (form.title.length > 50) {
    ElMessage.warning('标题长度不能超过50个字符')
    return
  }
  if (form.content.length > 2000) {
    ElMessage.warning('内容长度不能超过2000个字符')
    return
  }

  submitting.value = true
  try {
    const res = await createDiary({
      title: form.title,
      content: form.content,
      mood: form.mood,
      weather: form.weather,
      isPrivate: form.isPrivate
    })

    if (res.code === 200) {
      // 保存成功后清除草稿
      clearDraft()
      ElMessage.success('日记保存成功！')
      router.push('/diary')
    } else {
      ElMessage.error(res.msg || '保存日记失败')
    }
  } catch (error) {
    console.error('保存日记失败：', error)
    ElMessage.error('保存日记失败')
  } finally {
    submitting.value = false
  }
}

// 返回
const goBack = () => {
  router.back()
}
</script>

<style scoped>
.create-diary-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #ffeef8 0%, #fff5f7 100%);
  padding-bottom: 20px;
}

/* 顶部标题栏 */
.page-header {
  position: sticky;
  top: 0;
  z-index: 100;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  background: linear-gradient(135deg, #ff85c0 0%, #ff69b4 100%);
  box-shadow: 0 2px 8px rgba(255, 105, 180, 0.2);
}

.page-header h1 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: white;
  flex: 1;
  text-align: center;
}

.back-btn {
  background: rgba(255, 255, 255, 0.3);
  border: none;
  color: white;
  width: 36px;
  height: 36px;
}

.back-btn:hover {
  background: rgba(255, 255, 255, 0.5);
}

.placeholder {
  width: 36px;
}

/* 表单容器 */
.diary-form {
  margin: 16px;
  background: white;
  border-radius: 16px;
  padding: 20px 16px;
  box-shadow: 0 2px 12px rgba(255, 105, 180, 0.08);
}

/* 表单区块 */
.form-section {
  margin-bottom: 24px;
}

.section-label {
  font-size: 15px;
  font-weight: 600;
  color: #333;
  margin-bottom: 12px;
  display: flex;
  align-items: center;
}

.required {
  color: #ff4d4f;
  margin-right: 4px;
  font-size: 14px;
}

/* 标题输入框 */
.title-input {
  width: 100%;
}

:deep(.title-input .el-input__wrapper) {
  font-size: 15px;
  border-radius: 8px;
  border: 1px solid #e5e5e5;
  padding: 12px 15px;
  box-shadow: none;
}

:deep(.title-input .el-input__wrapper:hover) {
  border-color: #ff69b4;
}

:deep(.title-input .el-input__wrapper.is-focus) {
  border-color: #ff69b4;
  box-shadow: 0 0 0 1px rgba(255, 105, 180, 0.2);
}

/* 心情选项 */
.mood-options {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
}

.mood-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 12px 8px;
  background: #f8f8f8;
  border: 2px solid transparent;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.mood-item:active {
  transform: scale(0.95);
}

.mood-item.active {
  background: linear-gradient(135deg, #ffe8f5 0%, #fff0f8 100%);
  border-color: #ff69b4;
  box-shadow: 0 2px 8px rgba(255, 105, 180, 0.2);
}

.mood-emoji {
  font-size: 28px;
  margin-bottom: 4px;
}

.mood-text {
  font-size: 13px;
  color: #666;
  font-weight: 500;
}

.mood-item.active .mood-text {
  color: #ff69b4;
  font-weight: 600;
}

/* 天气选项 */
.weather-options {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
}

.weather-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 12px 8px;
  background: #f8f8f8;
  border: 2px solid transparent;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.weather-item:active {
  transform: scale(0.95);
}

.weather-item.active {
  background: linear-gradient(135deg, #e8f4ff 0%, #f0f8ff 100%);
  border-color: #4da6ff;
  box-shadow: 0 2px 8px rgba(77, 166, 255, 0.2);
}

.weather-emoji {
  font-size: 28px;
  margin-bottom: 4px;
}

.weather-text {
  font-size: 13px;
  color: #666;
  font-weight: 500;
}

.weather-item.active .weather-text {
  color: #4da6ff;
  font-weight: 600;
}

/* 内容输入框 */
.content-textarea {
  width: 100%;
}

:deep(.content-textarea .el-textarea__inner) {
  font-size: 14px;
  line-height: 1.8;
  border-radius: 8px;
  border: 1px solid #e5e5e5;
  padding: 12px 15px;
  font-family: inherit;
}

/* 隐私设置 */
.privacy-section {
  background: linear-gradient(135deg, #fff9e6 0%, #fffbf0 100%);
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 24px;
}

.privacy-label {
  font-size: 15px;
  font-weight: 600;
  color: #333;
  margin-bottom: 12px;
}

.privacy-switch {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.switch-label {
  font-size: 14px;
  color: #666;
  font-weight: 500;
}

/* 日记内容标签和清空按钮 */
.section-label-with-action {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}

.clear-btn {
  height: 28px;
  padding: 0 12px;
  font-size: 13px;
  border-radius: 14px;
  border: 1px solid #ff4d4f;
  color: #ff4d4f;
  background: white;
}

.clear-btn:hover {
  background: #fff1f0;
  border-color: #ff4d4f;
  color: #ff4d4f;
}

.clear-btn:active {
  transform: scale(0.95);
}

/* 底部按钮 */
.form-actions {
  display: flex;
  margin-top: 32px;
}

.submit-btn {
  width: 100%;
  height: 48px;
  font-size: 16px;
  font-weight: 600;
  border-radius: 24px;
  background: linear-gradient(135deg, #ff85c0 0%, #ff69b4 100%);
  border: none;
  box-shadow: 0 4px 12px rgba(255, 105, 180, 0.3);
}

.submit-btn:hover {
  background: linear-gradient(135deg, #ff69b4 0%, #ff5aa0 100%);
  box-shadow: 0 6px 16px rgba(255, 105, 180, 0.4);
}

.submit-btn:active {
  transform: scale(0.98);
}

/* 清空确认对话框按钮样式 */
:deep(.confirm-clear-btn) {
  background: #ff4d4f !important;
  border-color: #ff4d4f !important;
}

:deep(.confirm-clear-btn:hover) {
  background: #ff7875 !important;
  border-color: #ff7875 !important;
}

/* 响应式适配 - 平板及以上 */
@media (min-width: 768px) {
  .diary-form {
    max-width: 600px;
    margin: 24px auto;
    padding: 32px 28px;
  }

  .page-header h1 {
    font-size: 24px;
  }

  .mood-options,
  .weather-options {
    grid-template-columns: repeat(6, 1fr);
  }

  .form-actions {
    max-width: 400px;
    margin-left: auto;
    margin-right: auto;
  }
}

/* 响应式适配 - 大屏 */
@media (min-width: 1024px) {
  .diary-form {
    max-width: 800px;
    padding: 40px 36px;
  }
}
</style>

